package com.skyworth.web.admin.user.controller;

import com.google.gson.JsonObject;
import com.skyworth.web.admin.role.domain.RoleModel;
import com.skyworth.web.admin.role.service.RoleService;
import com.skyworth.web.admin.user.domain.UserKind;
import com.skyworth.web.admin.user.domain.UserModel;
import com.skyworth.web.admin.user.form.UserForm;
import com.skyworth.web.admin.user.service.UserService;
import com.skyworth.web.common.Constants;
import com.skyworth.web.common.controller.BaseController;
import com.skyworth.web.common.form.MenuCss;
import com.skyworth.web.common.form.Paginator;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by skyworth on 2016/6/23.
 */

@Controller
@RequestMapping("/admin/user")
public class UsersController extends BaseController{
    Logger LOG = LoggerFactory.getLogger(UsersController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private MenuCss menuCss;

    @Autowired
    private RoleService roleService;

    @RequiresRoles(value={Constants.USER_ROLE})
    @RequestMapping(value = {"users"}, method = RequestMethod.GET)
    public String index(Paginator paginator,Model model) {
        UserModel userModel = currentUser();
        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouUser = "hover";
        model.addAttribute("menuCss", menuCss);
        model.addAttribute("user", userModel);
        Page<UserModel> page = userService.userPage(null, paginator.pageRequest());
        paginator.feedToModel(page, model);

        return "admin/user/users";
    }

    @RequiresRoles(value={Constants.USER_ROLE})
    @RequestMapping(value = {"waiters"}, method = RequestMethod.GET)
    public String getWaiter(Paginator paginator,Model model) {
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }
        JsonObject params = new JsonObject();
        params.addProperty("store_id", store_id);
        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouUser = "hover";
        model.addAttribute("menuCss", menuCss);
        model.addAttribute("user", userModel);
        Page<UserModel> page = userService.userPage(params,paginator.pageRequest());
        paginator.feedToModel(page, model);

        return "admin/user/users";
    }

    @RequestMapping(value = {"new"})
    public String newAction(Model model) {
        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouUser = "hover";
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }
        List<RoleModel> roleModels = roleService.listRole(store_id);
        model.addAttribute("menuCss", menuCss);
        model.addAttribute("user", currentUser());
        model.addAttribute("roles", roleModels);

        return "admin/user/user_new";
    }


    @RequestMapping(value = {"{id}"}, method = RequestMethod.GET)
    public String edit(@PathVariable("id") long id, Model model) {
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }
        menuCss = new MenuCss();
        menuCss.currentFanfou = "show";
        menuCss.currentFanfouUser = "hover";

        model.addAttribute("menuCss", menuCss);

        List<RoleModel> roleModels = roleService.listRole(store_id);
        model.addAttribute("roles", roleModels);

        UserModel user = userService.findUser(id);
        model.addAttribute("user", currentUser());
        model.addAttribute("employee", user);

        return "admin/user/user_edit";
    }


    @RequestMapping(value = {"{id}"}, method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> update(@PathVariable("id") long id,
                         @ModelAttribute UserForm userForm,
                         Model model) {
        Map<String, Object> map = new HashMap<>();
        long store_id = 0;
        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }else {
            map.put("valid", false);
            map.put("errorMsg", "请先登陆");
            return map;
        }
        model.addAttribute("user", userModel);

        if(userService.existEmployee(userForm.getEmployeeNo(), id, store_id)){
            map.put("valid", false);
            map.put("errorMsg", userForm.getEmployeeNo()+"已存在");
            return map;
        }
        if(userService.existUser(userForm.getUsername(), id, store_id)){
            map.put("valid", false);
            map.put("errorMsg", userForm.getUsername()+"已存在");
            return map;
        }
        if(!userForm.getMobile().isEmpty() && userService.existPhone(userForm.getMobile(), id, store_id)){
            map.put("valid", false);
            map.put("errorMsg", userForm.getMobile()+"已存在");
            return map;
        }

        userForm.id = id;
        UserModel user = userService.updateUser(userForm);

        map.put("valid", true);
        if(userModel.kind==UserKind.ADMIN){
            map.put("url", "/admin/user/users");
        }else{
            map.put("url", "/admin/user/waiters");
        }
        return map;
    }

    @RequestMapping(value = {"{id}"}, method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") long id ) {
        Map<String, Object> rsp = responseMap();

        UserModel user = userService.findUser(id);

        if (user != null) {
            userService.removeUser(id);
        }else {
            rsp.put("success", false);
            rsp.put("message", "user doesn't exist");
        }

        return rsp;
    }


    @RequestMapping(value = {"create"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(@ModelAttribute UserForm userForm,
                          Model model) {
        Map<String, Object> map = new HashMap<>();
        long store_id = 0;

        UserModel userModel = currentUser();
        if(null != userModel){
            store_id = userModel.storeId;
        }else {
            map.put("valid", false);
            map.put("errorMsg", "请先登陆");
            return map;
        }
        model.addAttribute("user", userModel);

        List<RoleModel> roleModels = roleService.listRole(store_id);
        model.addAttribute("roles", roleModels);

        if(!userForm.getMobile().isEmpty() && userService.existsByMobile(userForm.getMobile(),store_id)){
            map.put("valid", false);
            map.put("errorMsg", userForm.getMobile()+"已存在");
            return map;
        }
        if(userService.existsByEmployeeNo(userForm.getEmployeeNo(),store_id)){
            map.put("valid", false);
            map.put("errorMsg", userForm.getEmployeeNo()+"已存在");
            return map;
        }
        if(userService.existsByUsername(userForm.getUsername(),store_id)){
            map.put("valid", false);
            map.put("errorMsg", userForm.getUsername()+"已存在");
            return map;
        }

        userForm.setStoreId(store_id);
        UserModel user = userService.addUser(userForm);
        if (user.id > 0) {
            map.put("valid", true);
            if(userModel.kind==UserKind.ADMIN){
                map.put("url", "/admin/user/users");
            }else{
                map.put("url", "/admin/user/waiters");
            }
        } else {
            map.put("valid", false);
            map.put("errorMsg", "员工添加失败");
        }
        return map;
    }
}
